package cn.lg.soar.message.service.impl;

import cn.lg.soar.message.service.IMailLogService;
import cn.lg.soar.message.service.IMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.ObjectUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author luguoxiang
 * @date 2022/4/5
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class MailServiceImpl implements IMailService {

    private final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private MailProperties mailProperties;
    /**
     * 必须配置邮件，否则这里报注入异常
     */
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private IMailLogService mailLogService;

    @Override
    public void send(String[] tos, String subject, String content, File...files) {
        // 发送带附件的邮件
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(tos);
            helper.setSubject(subject);
            helper.setText(content, true);

            // 处理附件
            if(!ObjectUtils.isEmpty(files)){
                for(File f : files){
                    FileSystemResource file = new FileSystemResource(f);
                    helper.addAttachment(f.getName(), file);
                }
            }
            mailSender.send(message);
            logger.info("发送邮件成功：subject = {}， tos = {}", subject, tos);
            mailLogService.successLog(subject, content, tos);
        } catch (MessagingException e) {
            logger.error("发送邮件失败：subject = {}， tos = {}", subject, tos, e);
            mailLogService.failLog(subject, content, tos);
        }
    }

}
